"""
session.py - Manual cookie-based session handling.
"""

import uuid
from http.cookies import SimpleCookie
import config

SESSIONS = {}


def get_session(handler):
    raw_cookie = handler.headers.get('Cookie', '')
    cookie = SimpleCookie(raw_cookie)
    sid = cookie.get(config.SESSION_COOKIE_NAME)
    if sid:
        sid = sid.value
        if sid in SESSIONS:
            handler._sid = sid
            handler._new_sid = False
            handler.session = SESSIONS[sid]
            handler._cookie_sent = True
            return handler.session

    sid = str(uuid.uuid4())
    SESSIONS[sid] = {}
    handler._sid = sid
    handler._new_sid = True
    handler.session = SESSIONS[sid]
    handler._cookie_sent = False
    return handler.session


def set_session_cookie(handler):
    """
    Call this BEFORE handler.end_headers().
    If the session is new, send a Set-Cookie header.
    """
    if getattr(handler, '_new_sid', False) and not getattr(handler, '_cookie_sent', False):
        cookie_str = f'{config.SESSION_COOKIE_NAME}={handler._sid}; Path=/; HttpOnly; SameSite=Lax'
        handler.send_header('Set-Cookie', cookie_str)
        handler._cookie_sent = True


def clear_session_cookie(handler):
    """
    Expire the session cookie by setting its value to empty
    and its expiration date in the past.
    """
    cookie_str = f'{config.SESSION_COOKIE_NAME}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0'
    handler.send_header('Set-Cookie', cookie_str)